package com.hc.java.lock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 互斥锁
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/6/8 10:24
 */
public class Mutex {
    private static class Sync extends AbstractQueuedSynchronizer {
        /**
         * state为0，表示锁没有被占用；当=1时，表示已被占用
         */
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }


        /**
         * 尝试获取锁，如果state=0，则获取成功；否则加入等待队列
         *
         * @param acquires
         * @return
         */
        @Override
        protected boolean tryAcquire(int acquires) {
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        /**
         * 释放锁
         *
         * @param releases
         * @return
         */
        @Override
        protected boolean tryRelease(int releases) {
            if (getState() == 0) throw new IllegalMonitorStateException();
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }
    }

    private final Sync sync = new Sync();

    /**
     * 获取锁
     */
    public void lock() {
        sync.acquire(1);
    }

    /**
     * 释放锁
     */
    public void unlock() {
        sync.release(1);
    }
}
